<template>
    <rx-layout>
        <div slot="left" width="200" showButton="true">
            <rx-fit>
                <rx-category-treeeditor
                    cat-key="BPM"
                    :statisticConfig="statisticConfig"
                    read-key="inst.read"
                    :edit="false"
                    @handSelect="selectTreeNode"
                    :async="true"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :treeRootList="treeRootList"
                    :isBpmClient="isBpmClient"
                ></rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center" style>
            <rx-fit :isheader="isheader">
                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
                    <div v-if="selectedRowKeys.length > 0" class="table-operator">
                        <a-button v-if="findAuthRight('inst.delete') && removeEnable" type="danger" icon="delete"
                                  @click="delByIds(selectedRowKeys)">{{ $ti18('rxList.delBtn', '删除') }}
                        </a-button>
                        <a-button v-show="selectedRowKeys.length == 1"  type="danger" icon="edit" @click="onLiveProcess">
                            {{ i18n('list.reviveProcess', '复活流程') }}
                        </a-button>
                    </div>

                    <span class="search-btn-box" v-if="!isheader">
                    <span class="search-btn" @click.stop="searchshow"><i
                        class="iconfont iconguolv"></i>{{ $ti18('rxList.leachBtn', '过滤') }}</span>
                    </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.subject', '标题')">
                                    <a-input :placeholder="i18n('form.subject', '标题','input')"
                                             v-model="queryParam['Q_i.SUBJECT__S_LK']"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.businessNum','业务单号')">
                                    <a-input :placeholder="i18n('form.businessNum','业务单号','input')"
                                             v-model="queryParam['Q_i.BILL_NO__S_LK']"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.runStatus','运行状态')">
                                    <a-select :placeholder="i18n('form.runStatus','运行状态','select')"
                                              v-model="queryParam['Q_i.STATUS__S_EQ']" allowClear>
                                        <a-select-option value="">{{ $ti18('rxDecorator.select', '请选择') }}..
                                        </a-select-option>
                                        <a-select-option v-for="(item,key) in statusMap" :value="key" :key="key">
                                            {{ item.text }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="isheader">
                                <span class="table-page-search-submitButtons">
                                    <a-button type="primary" icon="search"
                                              @click="search">{{ $ti18('rxList.searchBtn', '查询') }}</a-button>
                                    <a-button style="margin-left: 4px"
                                              @click="cancel">{{ $ti18('rxList.resetBtn', '重置') }}</a-button>
                                    <a @click="toggleAdvanced" style="margin-left: 8px">
                                      {{ advanced ? i18n('list.collapse', '收起') : i18n('list.expand', '展开') }}
                                      <a-icon :type="advanced ? 'up' : 'down'"/>
                                    </a>
                                </span>
                            </a-col>
                            <template v-if="advanced">
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.createTime','创建时间')">
                                        <a-range-picker format="YYYY-MM-DD" @change="createTimeChange" />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.archiveLogs','归档记录')">
                                        <a-select :placeholder="i18n('form.archiveLogs','归档记录','select')"
                                                  v-model="queryParam['tableId']" allowClear>
                                            <a-select-option v-for="(item,key) in bpmArchiveLogs" :key="item.tableId"
                                                             :value="item.tableId">{{ item.archiveDate }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                            </template>
                        </a-row>

                    </a-form>
                </div>

                <rx-grid
                    v-if="isShowManageTree"
                    ref="table"
                    bordered
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-bpm/bpm/core/bpmInst/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    id-field="instId"
                    :pageSizeOptions="['10','30','40']"
                    rowKey="instId"
                    :loadDataOnstart="true"
                    @selectChange="onSelectChange"
                    :srcoll="{x:1000}"
                >
                    <span slot="status" slot-scope="{ text,status }">
                        <a-tag :color="statusMap[text].color">
                            <span>{{ statusMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="isLive" slot-scope="{ text,status }">
                        <a-tag :color="isLiveMap[text].color">
                            <span>{{ isLiveMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="appId" slot-scope="{ text, record }">
                        {{ allApps[text] ? $i18(allApps[text].appName, '应用名称') : $ti18('rxList.noAppName', '无') }}
                    </span>
                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                    <span @click.stop="onDetail(record)">{{ i18n('list.details', '明细') }}</span>
                    <span @click.stop="openPermission(record)">{{ i18n('permissionManagement', '查阅权限') }}</span>
                    <template v-if="record.status=='DRAFT'">
                        <span @click.stop="startFlow(record)">{{ i18n('list.start', '启动') }}</span>
                    </template>
                    <template v-else>
                        <span v-show="record.status == 'SUPSPEND'"
                              @click.stop="restoreInst(record)">{{ i18n('list.restore', '恢复 ') }}</span>
                        <span v-show="record.status == 'RUNNING'"
                              @click.stop="supspendInst(record)">{{ i18n('list.suspend', '暂停') }}</span>
                        <span
                            v-show="findAuthRight('inst.intervene')&&record.status!='SUCCESS_END'&&record.status!='CANCEL'&&record.status!='ARCHIVED'"
                            @click.stop="operatorInst(record)">{{ i18n('list.intervene', '干预') }}</span>
                        <span v-show="record.status!='CANCEL'&&record.status!='ARCHIVED'"
                              @click.stop="cancelInst(record)">{{ i18n('list.cancel', '作废') }}</span>
                    </template>
                    <span v-if="findAuthRight('inst.delete') && removeEnable &&record.status!='ARCHIVED'"
                            @click.stop="delByIds([record.instId])">{{ $ti18('rxList.delBtn', '删除') }}</span>
                    <span v-if="record.status=='ARCHIVED'"
                            @click.stop="delArchive([record.instId])">{{ i18n('list.delBackUp', '删除备份') }}</span>
                    </span>
                </rx-grid>
            </rx-fit>
            <a-modal :title="i18n('cancelTips','流程作废提示')" v-model="cancelVisiable" @ok="onCancelInst">
                <p>{{ i18n('sureCancel', '您确定需要作废该流程吗？') }}</p>
                <p>{{ i18n('cancelReason', '作废原因：') }}</p>
                <p>
                    <a-textarea v-model="cancelReason"></a-textarea>
                </p>
            </a-modal>
        </div>

    </rx-layout>
</template>

<script>
import BpmInstApi from '@/api/bpm/core/bpmInst'
import BpmInstLiveSelect from "@/views/modules/bpm/core/BpmInstLiveSelect";
import BpmInstPermissionManagement from "@/views/modules/bpm/core/BpmInstPermissionManagement";
import RxCategoryTreeeditor from "@/components/redxun/rx-category-treeeditor";
import {BaseList, RxLayout, Util, RxGrid, RxFit} from '@lowcode/jpaas-common-lib'
import FlowUtil from "../js/FlowUtil";
import {mapState} from 'vuex';
import AppSearch from "@/views/modules/share/AppSearch";
import RxSearchApp from "@/views/modules/share/rx-search-app";
import instAndTaskShare from "@/views/modules/bpm/core/js/instAndTaskShare";
export default {
    name: 'BpmInstList',
    mixins: [BaseList,instAndTaskShare,FlowUtil,AppSearch],
    components: {
        RxLayout,
        RxGrid,
        RxCategoryTreeeditor,
        RxFit,
        RxSearchApp
    },
    computed: {
        ...mapState({
            // 所属应用
            allApps: state => state.appSetting ? state.appSetting.allApps : {}
        }),
    },
    data() {
        return {
            treeData: [],
            statusMap: {
                DRAFTED: {color: 'gray', text: this.i18n('option.draft', '草稿')},
                RUNNING: {color: 'red', text: this.i18n('option.running', '运行中')}, //运行
                SUPSPEND: {color: 'black', text: this.i18n('list.suspend', '暂停')}, //运行
                CANCEL: {color: 'red', text: this.i18n('list.cancel', '作废')}, //作废
                SUCCESS_END: {color: 'green', text: this.i18n('option.success', '成功')}, // 成功结束
                ERROR_END: {color: 'red', text: this.i18n('option.abort', '异常结束')}, //异常结束
                ARCHIVED: {color: 'green', text: this.i18n('option.placeOnFile', '归档')}, //归档
                LOCKED: {color: 'orange', text: this.i18n('option.lock', '驳回时锁定')},
                INVOKE_TO_STARTOR: {color: 'black', text: this.i18n('option.recall', '撤回到发起人')},
                RECOVER: {color: 'black', text: this.i18n('option.recover', '撤回')},
                PENDING: {color: 'blue', text: this.i18n('option.pending', '挂起')},
            },
            isLiveMap: {
                YES: {color: 'red', text: this.i18n('option.yes', '已复活')},
                NO: {color: 'green', text: this.i18n('option.no', '未复活')}
            },
            //归档记录
            bpmArchiveLogs: [],

            cancelVisiable: false,
            cancelInstId: '',
            cancelReason: '',//流程作废原因
            // 查询参数
            queryParam: {},
            // 表头
            columns: [
                {
                    key: '01',
                    title: this.$ti18('rxList.index', '序号'),
                    type: 'indexColumn',
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'},
                    width: 40
                },
                {
                    key: '02',
                    title: this.i18n('form.subject', '标题'),
                    dataIndex: 'subject',
                    width: 210
                },
                {
                    key: '03',
                    title: this.i18n('form.businessNum', '业务单号'),
                    dataIndex: 'billNo',
                    width: 110
                },
                {
                    title: this.i18n('form.application', '所属应用'),
                    dataIndex: 'appId',
                    width: 140,
                    sortField: 'APP_ID_',
                    scopedSlots: {customRender: 'appId'}
                },
                {
                    key: '04',
                    title: this.i18n('form.runStatus', '运行状态'),
                    dataIndex: 'status',
                    width: 100,
                    scopedSlots: {customRender: 'status'}
                },
                {
                    key: '07',
                    title: this.i18n('form.createTime', '创建时间'),
                    dataIndex: 'createTime',
                    width: 100
                },
                {
                    key: '08',
                    title: this.$ti18('rxList.action', '操作'),
                    dataIndex: 'action',
                    fixed: 'right',
                    scopedSlots: {customRender: 'action'},
                    width: Util.langSize({'zh-CN':120,'en-US':200,'ja-JP':200,'es-ES':210}),
                }
            ],
            curTree: {},
            statisticConfig: {
                type: "static_bpm",
                table: "BPM_INST",
                field: "TREE_ID_",
                whereConf: []
            },
            isBpmClient:true,
            readKey:"inst.read",
            treePrefix:'i.',
            appPrefix:"i."
        }
    },
    created() {
        this.getBpmArchiveLogs();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "bpmInst", key);
        },
        selectTreeNode(curRow) {
            this.loadDataBySelectTreeNode(curRow);
        },
        createTimeChange(dateArray,dateStrings){
            this.queryParam['Q_i.CREATE_TIME__D_GE']=dateStrings[0];
            this.queryParam['Q_i.CREATE_TIME__D_LE']=dateStrings[1];
        },
        openPermission(record) {
            Util.open({
                component: BpmInstPermissionManagement,
                curVm: this,
                widthHeight: ['1024px', '600px'],
                title: "【" + record.subject + "】" + this.i18n('permissionManagement', '查阅权限'),
                data: {
                    instId: record.instId
                }
            }, function (action, data) {
                if (action != 'ok') return;
            })
        },
        onDetail(record) {

            this.openDetail(record.appId, record.instId);
        },
        startFlow(record) {
            this.openInst(record.appId, record.instId);
        },
        operatorInst(record) {
            this.openOperator(record);
        },
        //恢复
        restoreInst(record) {
            BpmInstApi.updateProcessStatus(record.instId, 'RUNNING').then(resp => {
                this.refreshGrid();
            });
        },
        //挂起
        supspendInst(record) {
            BpmInstApi.updateProcessStatus(record.instId, 'SUPSPEND').then(resp => {
                this.refreshGrid();
            });
        },
        //显示取消流程窗口
        cancelInst(record) {
            this.cancelVisiable = true;
            this.cancelInstId = record.instId;
        },
        //执行作废
        onCancelInst() {
            let self_ = this;
            BpmInstApi.cancelProcess(this.cancelInstId, this.cancelReason).then(resp => {
                self_.cancelReason = '';
                self_.cancelInstId = '';
                self_.cancelVisiable = false;
                self_.refreshGrid();
            });
        },
        handleOk() {
            this.$refs.table.loadData()
        },
        delByIds(ids) {
            if (ids.length <= 0) {
                this.$notification.warning({
                    message: this.$ti18('rxMsa.tips', '提示'),
                    description: this.i18n('selectOne', '请最少选择一条要删除的数据'),
                    duration: 1.5,
                })
                return;
            }
            let self_ = this
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                content: this.$ti18('rxMsa.delInfo', '您确定需要删除选中的记录吗？'),
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                    BpmInstApi.delBpmInst({ids: ids.join(',')}).then(res => {
                        if (res.success && res.code == 200) {
                            self_.handleOk()
                        }
                        self_.selectedRowKeys = []
                    })
                },
                onCancel() {
                }
            })
        },
        onLiveProcess() {
            var row = this.$refs.table.getSelectedRow();
            if (!row || (row.status != "SUCCESS_END" && row.status != "ERROR_END")) {
                this.$message.error(this.i18n('unfinished', '无法复活未结束的流程！'));
                return;
            }
            if (row.isLive == "YES") {
                this.$message.error(this.i18n('resurrected', '无法复活已复活的流程！'));
                return;
            }
            var self_ = this;
            Util.open({
                component: BpmInstLiveSelect,
                curVm: this,
                widthHeight: ['1024px', '600px'],
                title: this.i18n('reviveInst', '类型编码') + "【" + row.subject + "】",
                data: {
                    instId: row.instId
                }
            }, function (action, data) {
                if (action != 'ok') return;
                BpmInstApi.liveProcess({
                    actInstId: row.actInstId,
                    destNodeUsers: data.destNodeUsers,
                    batchNodeGroups:data.batchNodeGroups,
                    opinion: data.opinion,
                    opFiles: data.opFiles
                }).then(res => {
                    self_.refreshGrid();
                })
            });
        },
        getBpmArchiveLogs() {
            BpmInstApi.getBpmArchiveLogs().then(res => {
                this.bpmArchiveLogs = res;
            });
        },
        delArchive(ids) {
            let self_ = this
            this.$confirm({
                title: this.$ti18('rxList.actionTips', '操作提示'),
                content: this.$ti18('rxMsa.delInfo', '您确定需要删除选中的记录吗？'),
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                    BpmInstApi.delArchive({ids: ids.join(',')}).then(res => {
                        if (res.success && res.code == 200) {
                            self_.handleOk();
                        }
                        self_.selectedRowKeys = []
                    })
                },
                onCancel() {
                }
            })
        },
        search() {
            this.$refs.table.loadData();
        },
        closeSearchbar() {
            //关闭过滤弹窗；（点击X触发）
            this.fitSearch = false;
        }
    }
}
</script>
<style>

</style>